<template>
    <el-form ref="formRef" label-width="90px" :model="form" :rules="rules">
        <el-form-item label="类别:" prop="category_id">
            <el-cascader v-model="form.category_id" :props="category_props" :options="categoryData.category_options"
                filterable clearable style="width: 100%;" />
        </el-form-item>
        <el-form-item label="信息标题:" prop="title">
            <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="缩略图:" prop="image_url">
            <el-upload ref="uploadRef" class="avatar-uploader" action="#" :limit="1" :multiple="false"
                :auto-upload="false" :show-file-list="false" :on-change="handleChange">
                <img v-if="form.image_url" :src="form.image_url" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="内容:" prop="content">
            <div style="border: 1px solid #ccc;width: 100%;">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                    :mode="mode" />
                <Editor style="height: 300px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                    :mode="mode" @onCreated="handleEditorCreated" @onChange="handleEditorChange" />
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="danger" @click="handleSubmit">确定</el-button>
            <el-button type="primary" @click="router.go(-1)">返回</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { reactive, toRefs, } from 'vue'
import { onBeforeUnmount, ref, shallowRef, onBeforeMount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' 
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useCategoryHook } from '@/hooks/categoryHook'
import useStore from '@/store'

const router = useRouter()
const route = useRoute()
const store = useStore()

const uploadRef = ref(null)
const formRef = ref(null)

const editorRef = shallowRef()

const { categoryData, getAllCategory } = useCategoryHook()

const validate_content_rules = (rule, value, callback) => {
    const editor = editorRef.value
    if (editor.isEmpty()) {
        callback(new Error('内容不能为空'))
    } else {
        callback()
    }
}

const data = reactive({
    category_props: {
        label: 'name',
        value: 'id'
    },
    file: null,
    form: {
        category_id: [],
        title: '',
        image_url: '',
        content: ''
    },
    rules: {
        category_id: [
            { required: true, message: '类别不能为空', trigger: 'change' }
        ],
        title: [
            { required: true, message: '标题不能为空', trigger: 'change' }
        ],
        image_url: [
            { required: true, message: '请上传缩略图', trigger: 'change' }
        ],
        content: [
            {
                required: true,
                validator: validate_content_rules,
                trigger: 'change'
            }
        ]
    },
    row_id: route.query.id
})

const { category_props, form, rules } = toRefs(data)

const checkUploadFile = (rawFile) => {
    console.log('file.size', rawFile.size);

    if (rawFile.size / 1024 > 200) {
        ElMessage.error('上传的文件大小不能超过200k!')
        return false
    }
    return true
}

const handleChange = (file) => {
    if (!checkUploadFile(file)) return
    data.file = file.raw
    form.value.image_url = URL.createObjectURL(file.raw)
    uploadRef.value.clearFiles()
}

const mode = 'default'


const valueHtml = ref('')

const toolbarConfig = {}

toolbarConfig.excludeKeys = ['group-video', 'insertTable', 'fullScreen']

// 图片上传
const editorConfig = { 
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        try {
          const formData = new FormData()
          formData.append('file', file)
          
          const res = await store.info.uploadFileAction(formData)
          
          if (res && res.data) {
            const imageUrl = res.data.url || res.data.image_url || res.data.path
            
            if (imageUrl) {
              insertFn(imageUrl, file.name, imageUrl)
              ElMessage.success('图片上传成功')
            } else {
              ElMessage.error('图片上传失败：未获取到图片URL')
            }
          } else {
            ElMessage.error('图片上传失败')
          }
        } catch (error) {
          console.error('图片上传失败:', error)
          ElMessage.error('图片上传失败')
        }
      },
      

      maxFileSize: 2 * 1024 * 1024, // 2M
      allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleEditorCreated = (editor) => {
    editorRef.value = editor
}

const handleEditorChange = (editor) => {
    form.value.content = editor.getHtml()
}

const getInfiDetail = async () => {
    const res = await store.info.getInfoDetailAction(data.row_id)
    console.log('res', res);
    const res_data = res.data
    data.form = res_data
    data.form.image_url = res.data['public_image_url']
    valueHtml.value = res_data.content
}

onBeforeMount(async () => {
    await getAllCategory()
    data.row_id && (await getInfiDetail())
})

const format_params = () => {
    const { category_id, title, content } = form.value
    const fd = new FormData()
    fd.append('category_id', Array.isArray(category_id) ? category_id[category_id.length - 1] : category_id)
    fd.append('title', title)
    fd.append('content', content)
    fd.append('file', data.file)
    return fd
}

const handleCreateInfo = async() => {
    const res = await store.info.createInfoAction(format_params())
    ElMessage.success(res.msg)
    router.back()
}

const handleUpdateInfo = async() => {
    const res = await store.info.updateInfoAction({ id:data.row_id,data:format_params()})
    ElMessage.success(res.msg)
    router.back()
}

const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            data.row_id ? await handleUpdateInfo() : await handleCreateInfo()
        }
    })
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>